package com.liuwei.spring.cloud.framework.feigns.caller;
/**
 * @author : FeignInterceptor
 * @version V1.0
 * @date: 2024/4/25 11:05 AM
 * @Description: TODO
 */
import com.liuwei.spring.cloud.common.utils.StringPool;
import com.liuwei.spring.cloud.framework.spring.ApplicationHelper;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class FeignBaggageInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //传递令牌
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null){
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request != null){
                String callerCluster = ApplicationHelper.getApplicationCluster();
                String callerApplication = ApplicationHelper.getApplicationName();

                requestTemplate.header(StringPool.Feign_Invoker,StringPool.ONE);
                requestTemplate.header(StringPool.Feign_Caller_Cluster,callerCluster);
                requestTemplate.header(StringPool.Feign_Caller_Application,callerApplication);

                // 添加 Baggage 信息
                String callerBaggage = request.getHeader(StringPool.Feign_Caller_Baggage);
                requestTemplate.header(StringPool.Feign_Caller_Baggage,callerBaggage);
            }
        }
    }
}
